package jus.aor.talk.v5;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Pattern;

import jus.aor.talk.MessageSay;

public class LetterBox {
	private String forum;
	private String nom;
	private String prenom;
	private ArrayList<MessageSay> messages;
	private String logFileName;
	
	public LetterBox(String forum, String nom, String prenom) {
		this.forum = forum;
		this.nom = nom;
		this.prenom = prenom;
		this.messages = new ArrayList<MessageSay>();
		this.logFileName = "logBAL" + nom + "_" + prenom + "_" + forum + ".txt";
		deleteLogFile();
	}
	
	public LetterBox(String logFileName) throws Exception {
		Pattern p = Pattern.compile("logBAL([a-zA-Z0-9]*)_([a-zA-Z0-9]*)_([a-zA-Z0-9]*).txt");
		if(p.matcher(logFileName).matches()) {
			this.messages = new ArrayList<MessageSay>();
			this.logFileName = logFileName;
			this.nom = p.matcher(logFileName).group(1);
			this.prenom = p.matcher(logFileName).group(2);
			this.forum = p.matcher(logFileName).group(3);
			FileInputStream file = new FileInputStream(logFileName);
			DataInputStream in = new DataInputStream(file);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null)   {
				Pattern p1 = Pattern.compile(".* / ([a-zA-Z0-9]*) ([a-zA-Z0-9]*):([a-zA-Z0-9]*)\n");
				MessageSay m = new MessageSay(p1.matcher(strLine).group(1), p1.matcher(strLine).group(2), p1.matcher(strLine).group(3));
				this.messages.add(m);
			}
			deleteLogFile();
		}
		else {
			throw new Exception("Filename doesn't match");
		}
	}
	
	public String getForum() {
		return forum;
	}
	
	public String getNom() {
		return nom;
	}
	
	public String getPrenom() {
		return prenom;
	}
	
	public ArrayList<MessageSay> getMessages() {
		return this.messages;
	}
	
	public void addMessage(MessageSay m) {
		this.messages.add(m);
		this.log(m);
	}
	
	private void log(MessageSay m) {
		try {
			FileOutputStream file = new FileOutputStream(logFileName, true);
			String line = "" + (new Date()).toString() + " / " + m.nom + " " + m.prenom + ":" + m.message + "\n";
			file.write(line.getBytes());
			file.close();
		}
		catch(Exception e) {
			System.err.println(e);
		}
	}
	
	public void deleteLogFile() {
		File file = new File(logFileName);
		if(file.exists()) {
			file.delete();
		}
	}
}
